<template>
  <view>
    <!-- 用户信息区域 - 增强版 -->
    <view class="user-info-card" v-if="isLoggedIn">
      <view class="card-background"></view>
      <view class="user-main-info">
        <view class="avatar-wrapper">
          <view class="avatar-ring"></view>
          <image 
            v-if="userAvatar" 
            :src="userAvatar" 
            class="user-avatar-enhanced"
            mode="aspectFill"
            @error="handleAvatarError"
          />
          <view v-else class="default-avatar-enhanced">
            <text class="avatar-text-large">{{ userName ? userName.charAt(0) : 'U' }}</text>
          </view>
        </view>
        <view class="user-details">
          <view class="greeting-row">
            <text class="greeting-title">Hi, {{ userName || '用户' }}! 👋</text>
            <!-- 管理员徽章 -->
            <view v-if="isAdmin" class="admin-badge" @click="handleAdminClick">
              <text class="badge-icon">👑</text>
              <text class="badge-text">管理员</text>
            </view>
          </view>
          <view class="user-stats-row">
            <text class="greeting-subtitle-new">今天也要加油哦 💪</text>
            <!-- 金币显示 -->
            <view class="gold-display-overview" :class="{ 'gold-increase': isGoldIncreasing }">
              <text class="gold-icon-overview">🪙</text>
              <text class="gold-amount-overview">{{ currentGold }}</text>
              <view v-if="showGoldAnimation" class="gold-animation-overview">+1</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 欢迎内容 -->
    <view class="welcome-content" v-else>
      <view class="welcome-info">
        <text class="welcome-title">欢迎使用</text>
        <text class="welcome-subtitle">请先登录以使用完整功能</text>
      </view>
      <view class="welcome-actions">
        <button class="login-btn" @click="handleLogin">登录</button>
        <button class="register-btn" @click="handleRegister">注册</button>
      </view>
    </view>
  </view>
</template>

<script>
import goldManager from '@/utils/gold-manager.js'

export default {
  name: 'UserInfoCard',
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userName: {
      type: String,
      default: ''
    },
    userAvatar: {
      type: String,
      default: ''
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentGold: 0,
      isGoldIncreasing: false,
      showGoldAnimation: false,
      goldTimer: null
    }
  },
  // Vue 生命周期
  created() {
    // 组件创建时，如果已登录则初始化
    if (this.isLoggedIn) {
      this.$nextTick(() => {
        this.initGoldSystem()
      })
    }
  },
  
  beforeDestroy() {
    // 组件销毁前清理
    this.stopGoldTimer()
  },
  
    watch: {
    isLoggedIn: {
      immediate: true, // 立即执行一次
      handler(newVal, oldVal) {
        console.log('isLoggedIn 变化:', oldVal, '->', newVal)
        if (newVal) {
          // 延迟初始化，确保数据已加载
          this.$nextTick(() => {
            this.initGoldSystem()
          })
        } else {
          // 退出登录时，停止计时器并记录退出时间
          this.stopGoldTimer()
          goldManager.recordLogoutTime()
          this.currentGold = 0
        }
      }
    }
  },
  methods: {
    // 初始化金币系统
    initGoldSystem() {
      // 检查登录状态
      if (!this.isLoggedIn) {
        console.warn('未登录，无法初始化金币系统')
        this.stopGoldTimer()
        return
      }

      console.log('初始化金币系统')
      
      // 计算并添加离线收益
      this.processOfflineReward()
      
      this.loadGold()
      this.startGoldTimer()
    },
    
    // 处理离线收益
    processOfflineReward() {
      const rewardInfo = goldManager.calculateOfflineReward()
      
      if (rewardInfo.offlineGold > 0) {
        // 添加离线收益
        goldManager.addOfflineReward(rewardInfo.offlineGold)
        
        // 显示离线收益提示
        const hours = Math.floor(rewardInfo.offlineSeconds / 3600)
        const minutes = Math.floor((rewardInfo.offlineSeconds % 3600) / 60)
        let timeText = ''
        if (hours > 0) {
          timeText = `${hours}小时${minutes}分钟`
        } else if (minutes > 0) {
          timeText = `${minutes}分钟`
        } else {
          timeText = `${rewardInfo.offlineSeconds}秒`
        }
        
        // 使用新的 Toast 组件显示离线收益
        toastHelper.showSuccess('离线收益', `离线${timeText}，获得${rewardInfo.offlineGold}金币`)
        
        console.log(`离线收益: ${rewardInfo.offlineGold}金币 (离线${timeText})`)
      }
    },
    
    // 加载金币
    loadGold() {
      const gold = goldManager.getCurrentGold() || 0
      console.log('加载金币:', gold)
      this.currentGold = gold
      // 强制更新视图
      this.$forceUpdate()
    },
    
    // 启动金币计时器
    startGoldTimer() {
      // 检查登录状态
      if (!this.isLoggedIn) {
        console.warn('未登录，无法启动金币计时器')
        this.stopGoldTimer()
        return
      }
      
      this.stopGoldTimer()
      
      // 确保有初始数据
      const goldData = goldManager.getGoldData()
      if (!goldData) {
        // 如果没有数据，初始化
        const initData = {
          gold: 0,
          recentActivities: [],
          lastUpdateTime: new Date().toISOString()
        }
        goldManager.saveGoldData(initData)
        this.currentGold = 0
      } else {
        // 更新当前金币显示
        this.currentGold = goldData.gold || 0
        // 如果距离上次更新超过1秒，补偿金币（但不超过60秒，避免异常）
        if (goldData.lastUpdateTime) {
          const now = Date.now()
          const lastUpdate = new Date(goldData.lastUpdateTime).getTime()
          const diffSeconds = Math.floor((now - lastUpdate) / 1000)
          if (diffSeconds > 1 && diffSeconds <= 60) {
            // 如果距离上次更新超过1秒但不超过60秒，立即增加金币（不显示动画）
            for (let i = 0; i < diffSeconds; i++) {
              this.addGoldPerSecond(false)
            }
          }
        }
      }
      
      // 每秒增加1金币（需要检查登录状态）
      this.goldTimer = setInterval(() => {
        // 每次执行前都检查登录状态
        if (!this.isLoggedIn) {
          console.warn('检测到未登录，停止金币计时器')
          this.stopGoldTimer()
          goldManager.recordLogoutTime()
          return
        }
        this.addGoldPerSecond()
      }, 1000)
    },
    
    // 停止金币计时器
    stopGoldTimer() {
      if (this.goldTimer) {
        clearInterval(this.goldTimer)
        this.goldTimer = null
      }
    },
    
    // 每秒增加金币
    addGoldPerSecond(showAnimation = true) {
      if (showAnimation) {
        this.showGoldAnimation = true
        this.isGoldIncreasing = true
        
        setTimeout(() => {
          this.showGoldAnimation = false
          this.isGoldIncreasing = false
        }, 600)
      }
      
      // 增加金币
      const success = goldManager.addGold(1, '宠物金币玩法')
      if (success) {
        const newGold = goldManager.getCurrentGold()
        // console.log('金币增加:', this.currentGold, '->', newGold)
        this.currentGold = newGold
        // 强制更新视图
        this.$forceUpdate()
      }
      
      // 更新最后更新时间
      const goldData = goldManager.getGoldData()
      if (goldData) {
        goldData.lastUpdateTime = new Date().toISOString()
        goldManager.saveGoldData(goldData)
      }
    },
    handleAvatarError() {
      this.$emit('avatar-error')
    },
    handleAdminClick() {
      this.$emit('admin-click')
    },
    handleLogin() {
      this.$emit('login')
    },
    handleRegister() {
      this.$emit('register')
    }
  }
}
</script>

<style scoped>
/* 用户信息卡片 - 增强版 */
.user-info-card {
  position: relative;
  background: white;
  border-radius: 24rpx;
  padding: 32rpx 28rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.card-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  opacity: 0.5;
}

.user-main-info {
  position: relative;
  display: flex;
  align-items: center;
  gap: 20rpx;
  z-index: 1;
}

.avatar-wrapper {
  position: relative;
}

.avatar-ring {
  position: absolute;
  top: -6rpx;
  left: -6rpx;
  right: -6rpx;
  bottom: -6rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0.2;
  animation: pulse-ring 3s ease-in-out infinite;
}

@keyframes pulse-ring {
  0%, 100% { transform: scale(1); opacity: 0.2; }
  50% { transform: scale(1.05); opacity: 0.3; }
}

.user-avatar-enhanced {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  border: 4rpx solid white;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
}

.default-avatar-enhanced {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4rpx solid white;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
}

.avatar-text-large {
  color: white;
  font-size: 40rpx;
  font-weight: bold;
}

.user-details {
  flex: 1;
}

.greeting-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.greeting-title {
  font-size: 32rpx;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.admin-badge {
  display: flex;
  align-items: center;
  gap: 6rpx;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  padding: 6rpx 14rpx;
  border-radius: 14rpx;
  box-shadow: 0 2rpx 8rpx rgba(251, 191, 36, 0.3);
  animation: badge-glow 2s ease-in-out infinite;
}

@keyframes badge-glow {
  0%, 100% { box-shadow: 0 2rpx 8rpx rgba(251, 191, 36, 0.3); }
  50% { box-shadow: 0 4rpx 12rpx rgba(251, 191, 36, 0.5); }
}

.badge-icon {
  font-size: 18rpx;
}

.badge-text {
  font-size: 20rpx;
  font-weight: bold;
  color: #d97706;
}

.greeting-subtitle-new {
  font-size: 24rpx;
  color: #6b7280;
  display: block;
}

.user-stats-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

/* 总览金币显示 */
.gold-display-overview {
  display: flex;
  align-items: center;
  gap: 6rpx;
  position: relative;
  padding: 8rpx 16rpx;
  background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
  border-radius: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(253, 203, 110, 0.3);
  transition: all 0.3s ease;
}

.gold-display-overview.gold-increase {
  animation: goldPulseOverview 0.6s ease;
  transform: scale(1.1);
}

@keyframes goldPulseOverview {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.15);
  }
  100% {
    transform: scale(1);
  }
}

.gold-icon-overview {
  font-size: 24rpx;
  animation: coinRotateOverview 2s linear infinite;
}

@keyframes coinRotateOverview {
  0% {
    transform: rotateY(0deg);
  }
  50% {
    transform: rotateY(180deg);
  }
  100% {
    transform: rotateY(360deg);
  }
}

.gold-amount-overview {
  font-size: 24rpx;
  font-weight: bold;
  color: #fdcb6e;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}

.gold-animation-overview {
  position: absolute;
  top: -25rpx;
  right: 0;
  font-size: 20rpx;
  font-weight: bold;
  color: #fdcb6e;
  animation: goldFloatOverview 0.6s ease-out forwards;
  pointer-events: none;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

@keyframes goldFloatOverview {
  0% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
  100% {
    opacity: 0;
    transform: translateY(-30rpx) scale(1.2);
  }
}

/* 欢迎内容 */
.welcome-content {
  background: white;
  border-radius: 24rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  text-align: center;
}

.welcome-info {
  margin-bottom: 32rpx;
}

.welcome-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #1f2937;
  display: block;
  margin-bottom: 12rpx;
}

.welcome-subtitle {
  font-size: 24rpx;
  color: #6b7280;
  display: block;
}

.welcome-actions {
  display: flex;
  gap: 16rpx;
}

.login-btn,
.register-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: none;
  transition: all 0.3s ease;
}

.login-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 6rpx 16rpx rgba(102, 126, 234, 0.4);
}

.register-btn {
  background: white;
  color: #667eea;
  border: 2rpx solid #667eea;
}

.login-btn:active,
.register-btn:active {
  transform: scale(0.96);
}
</style>

